/** 依赖于ajaxupload.js*/
Touchjs.addModule("uploadImage", ".touchjs-uploadimage", function(contentE) {
	var dealEle = findAndMarkEle(contentE, this.expression);
	if (dealEle.length > 0) {
		var $ = jQuery;
		dealEle.each(function() {
			var ele = $(this);
			var loadIndex; //加载中的下标
			var append = ele.data("append"); //追加多文件
			var fileNumber = 0; // 文件上传的次数
			var _default = {  		//默认配置参数
					'name' : 'file',   //上传时流的文件名称
					'fileType' : 'images',  //上传 类型     目前可选参数   (images:图片 ,file:文件)
					'exts' : 'jpg|png|bmp|jpeg|gif|JPG|PNG|BMP|GIF|JPEG', //上传文件的后缀 限制  自定义
					'uploadURL' : uploadUeRootPath+'/redirect?action=uploadimage&encode=utf-8&sendRedirect='+uploadCallbackURL + '&uploadGroup='+uploadGroup, //上传的路径     详情见mytags.jsp  有默认参数
					'uploadButton' : '#uploadButton', //需要绑定上传的按钮，建议用id参数
					'fileNumber' : 1 // 默认限制1个
				};
			var options = getExtendSettings(ele, _default);
			// 删除计数器
			$(document).on("click", options.deleteUpload, function() {
				var $this = $(this);
				$this.closest("div").empty(); // 删除div
				fileNumber = fileNumber - 1;
			});
			
		   	var parE = ele.closest(".uploadContainer");
        	if (parE.length == 0) {
        		parE = ele.parent();
            }
        	
        	var filePathE = parE.find(".imgPath");
        	var listE = parE.find(".img"); //新上传的
			new AjaxUpload(ele, {
				// 文件上传地址 action
				// ://http://upload.credithegs.gov.cn/affixUpload?callback=http://localhost:8081/uploadCallback&serverLocation=&type=2
				// 图片上传你地址 action : settings.uploadUeRootPath +
				// "?action=uploadimage&sendRedirect=" + ctxPath + "/" +
				// settings.uploadCallbackURL,
				action : options.uploadURL,
				name : options.name,
				onSubmit : function(file, ext) {
					if (fileNumber > Number(options.fileNumber)) { // 先校验个数
						Touchjs.error("上传失败，超过最大个数" + fileNumber);
						return false;
					}
					if ("images" == options.fileType) {
						if (options.exts != "*") {
							if (ext && new RegExp("^(" + options.exts + ")$").test(ext)) {
								this.setData({
									'info' : '文件类型为图片'
								});
							} else {
								// alert()
								Touchjs.error('文件格式错误，请上传格式为' + options.exts + ' 的图片');
								return false;
							}
						}

					} else if ("file" == options.fileType) {
						if (options.exts != "*") {
							if (ext && new RegExp("^(" + options.exts + ")$").test(ext)) {
								this.setData({
									'info' : '文件类型'
								});
							} else {
								Touchjs.error('文件格式错误，请上传格式为' + options.exts + '的文件');
								return false;
							}
						}
					} else {
						Touchjs.error('fileType参数错误！');
						return false;
					}
					loadIndex = layer.load(2);
					this.disable();

				},
				onComplete : function(file, response) {
					layer.close(loadIndex);
					try {
						var response = $.parseJSON(response); //返回的response为字符串重新处理为json
						console.log(response);
						if (response && response.state=="SUCCESS") {
							console.log(append);
							if (append) { // 多文件上传
				        		var pathOld = filePathE.val()?(filePathE.val()+'#'):'';
				        		filePathE.val(pathOld+response.url);
				        		if (parE.find(".nopic").length!=0) {
				        			parE.find(".imgShow").attr("src", response.url);
				        			parE.find(".nopic").removeClass("nopic");
				        		 	parE.find(".imgShow").after('<div style="text-align: center;" class="delimageNews" ><a>删除</a></div>');
			        			} else {
			        				listE.append('<div style="float:left;"><img  class="imgShow" name="imageNews" width="70" height="70" src="'+response.url+'" style="margin: 0 5px 10px; border: 1px solid #eee;  ">  <div style="text-align: center;" class="delimageNews" ><a>删除</a></div></div>')
		        				}
		                    } else {
					        	parE.find(".imgPath").val(response.url);
					        	parE.find(".imgShow").attr("src", response.url);
					        	if (parE.find(".imgShow").next('.delimageNews').length==0) {
					        		parE.find(".imgShow").after('<div style="text-align: center;" class="delimageNews" ><a>删除</a></div>');
				        		}
							}
			            } else {
			            	Touchjs.error(response.state);
			            }
						this.enable();
					} catch (e) {
						console.log(e);
						//error(e, response);
					}
				},
				onError:function(e) {
					layer.close(loadIndex); //关闭加载中
					// SecurityError: Permission denied to access property "document" on cross-origin object
					var message = "上传出错！";
					if(console){
						console.log(e);
					}
					var eMsg = e + "";
					if (eMsg.indexOf("cross-origin")!=-1) {
						message = "跨域上传权限错误！";
                    }
					Touchjs.error(message); 
					this.enable();
				}
			});
			// 删除
			parE.on('click','.delimageNews',function(){
				var delimageNews = parE.find(".delimageNews");
				var imgShow = parE.find(".imgShow");
				var thisIndex = delimageNews.index($(this));
				delimageNews.eq(thisIndex).remove();
				imgShow.eq(thisIndex).remove();
				//
				var imgPathSrc ="";
				parE.find(".imgShow").each(function(i){
					var srcPath = $(this).attr("src");
					if (srcPath) {
                    	if (i==0) {
                    		imgPathSrc = srcPath;
                		} else {
                			imgPathSrc += '#' + srcPath;
            			}
                    }
				})
				if(!imgPathSrc) {
					listE.append('<img class="imgShow nopic" name="imageNews" width="70" src="'+ctxPath+'/images/project/nopic.jpg" style="border: 1px solid #eee;" >')
				}
				parE.find(".imgPath").val(imgPathSrc);
			});
			
        });
	}
}, "图片上传（AjaxUpload版）");
